package br.com.amadeus.android.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class HttpConnection {
	
	static HttpURLConnection conn = null;
	
	
	public static void openConnection(String url) throws IOException{
		// Cria a URL
		URL u = new URL(url);
		conn = (HttpURLConnection) u.openConnection();
		conn.setRequestMethod("GET");
		conn.setDoInput(true);
		conn.setDoOutput(false);
		conn.connect();
	}
	
		
	public static HttpURLConnection getConn() {
		return conn;
	}
	
	public static void stopDownload(){
		conn.disconnect();
	}
	
	// Faz a leitura do texto da InputStream retornada
	public static String readString(InputStream in) throws IOException {
		byte[] bytes = readBytes(in);
		String texto = new String(bytes);
		return texto;
	}
	
	// Faz a leitura do array de bytes da InputStream retornada
	private static byte[] readBytes(InputStream in) throws IOException {
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			byte[] buffer = new byte[2048];
			int len;
			while ((len = in.read(buffer)) > 0) {
				bos.write(buffer, 0, len);
			}
			byte[] bytes = bos.toByteArray();
			return bytes;
		} finally {
			bos.close();
			in.close();
		}
	}


}
